package cn.com.anypay.manager.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 加密工具类
 * 提供常用的加密解密功能
 */
public final class CryptoUtils {

    private static final Logger logger = LoggerFactory.getLogger(CryptoUtils.class);

    private static final String AES_ALGORITHM = "AES";
    private static final String AES_TRANSFORMATION = "AES/ECB/PKCS5Padding";

    // 防止实例化
    private CryptoUtils() {}

    /**
     * MD5 加密
     */
    public static String md5(String input) {
        if (StringUtils.isBlank(input)) {
            return null;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hashBytes);
        } catch (Exception e) {
            logger.error("MD5 加密失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * SHA256 加密
     */
    public static String sha256(String input) {
        if (StringUtils.isBlank(input)) {
            return null;
        }
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = sha.digest(input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hashBytes);
        } catch (Exception e) {
            logger.error("SHA256 加密失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * SHA512 加密
     */
    public static String sha512(String input) {
        if (StringUtils.isBlank(input)) {
            return null;
        }
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-512");
            byte[] hashBytes = sha.digest(input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hashBytes);
        } catch (Exception e) {
            logger.error("SHA512 加密失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * AES 加密
     */
    public static String aesEncrypt(String data, String key) {
        if (StringUtils.isBlank(data) || StringUtils.isBlank(key)) {
            return null;
        }
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
            Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            logger.error("AES 加密失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * AES 解密
     */
    public static String aesDecrypt(String encryptedData, String key) {
        if (StringUtils.isBlank(encryptedData) || StringUtils.isBlank(key)) {
            return null;
        }
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
            Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.error("AES 解密失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 生成随机 AES 密钥
     */
    public static String generateAESKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(AES_ALGORITHM);
            keyGenerator.init(256);
            byte[] keyBytes = keyGenerator.generateKey().getEncoded();
            return Base64.getEncoder().encodeToString(keyBytes);
        } catch (Exception e) {
            logger.error("生成 AES 密钥失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 生成随机盐值
     */
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    /**
     * 密码加盐哈希
     */
    public static String hashPassword(String password, String salt) {
        if (StringUtils.isBlank(password) || StringUtils.isBlank(salt)) {
            return null;
        }
        String saltedPassword = password + salt;
        return sha256(saltedPassword);
    }

    /**
     * 验证密码
     */
    public static boolean verifyPassword(String password, String salt, String hashedPassword) {
        if (StringUtils.isBlank(password) || StringUtils.isBlank(salt) || StringUtils.isBlank(hashedPassword)) {
            return false;
        }
        String computedHash = hashPassword(password, salt);
        return hashedPassword.equals(computedHash);
    }

    /**
     * Base64 编码
     */
    public static String base64Encode(String input) {
        if (StringUtils.isBlank(input)) {
            return null;
        }
        return Base64.getEncoder().encodeToString(input.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * Base64 解码
     */
    public static String base64Decode(String encodedInput) {
        if (StringUtils.isBlank(encodedInput)) {
            return null;
        }
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(encodedInput);
            return new String(decodedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.error("Base64 解码失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 字节数组转十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    /**
     * 生成随机字符串
     */
    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }
}